package org.darkforest.common.services.impl;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.darkforest.common.services.GiftService;
import org.darkforest.common.services.MessageAndNoticeService;
import org.darkforest.common.services.SettingService;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.util.JacksonsUtil;
import org.darkforest.common.util.SerialNumGenerator;
import org.darkforest.dao.mapper.*;
import org.darkforest.enums.SettingNameEnum;
import org.darkforest.model.*;
import org.darkforest.vo.AjaxReturnData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/4/26.
 */
@Service
public class GiftServiceImpl implements GiftService {
    Logger logger = Logger.getLogger(GiftServiceImpl.class);

    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderGiftCodeMapper orderGiftCodeMapper;
    @Autowired
    private OrderCommonMapper orderCommonMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private GiftReceiveRecordMapper giftReceiveRecordMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private SettingService settingService;
    @Autowired
    private MessageAndNoticeService messageAndNoticeService;
    @Autowired
    private MemberMsgTplMapper memberMsgTplMapper;

    @Override
    public AjaxReturnData doReceiveGift(Address address, String giftCode, Member member) throws Exception {
        AjaxReturnData ajaxReturnData = new AjaxReturnData();
        OrderGiftCode orderGiftCode = orderGiftCodeMapper.selectByGiftCode(giftCode);

        Long ORDER_BATCH_NUMBER = SerialNumGenerator.getOrderBatchNum();
        //判断礼品码是否存在
        //判断礼品码是否有效
        if (orderGiftCode == null) {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setMessage("礼品码不存在");
        } else if (orderGiftCode.getCodeState() == 3) {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setMessage("礼品码已注销");
        } else if (orderGiftCode.getCodeState() == 2 && orderGiftCode.getUseMemberId() != member.getMemberId()) {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setMessage("礼品码已被使用");
        } else {
//            if(address.getAddressId() == null || address.getAddressId().intValue() == 0){
//                //收货地址插入数据库
//                address.setMemberId(member.getMemberId());
//                addressMapper.insertSelective(address);
//            }else{
//                address = addressMapper.selectByPrimaryKey(address.getAddressId());
//            }
            // 领取礼品时，ddressId都为空,需要根据memberId、trueName、regionId、areaId、cityId、address、mobPhone重新取得
            Address addressTemp =  new Address();
            addressTemp.setMemberId(member.getMemberId());
            addressTemp.setTrueName(address.getTrueName());
            addressTemp.setRegionId(address.getRegionId());
            addressTemp.setAreaId(address.getAreaId());
            addressTemp.setCityId(address.getCityId());
            addressTemp.setAddress(address.getAddress());
            addressTemp.setMobPhone(address.getMobPhone());
            List<Address> addressesList = addressMapper.selectAddressByCondition(addressTemp);
            if (addressesList == null || addressesList.size() == 0) {
                //收货地址插入数据库
                address.setMemberId(member.getMemberId());
                /*******
                 * 处理省市区名称展示
                 */
                String regionName = this.areaName(address.getRegionId());
                String cityName = this.areaName(address.getCityId());
                String areaName = this.areaName(address.getAreaId());
                address.setRegionName(regionName);
                address.setCityName(cityName);
                address.setAreaName(areaName);
                address.setAreaInfo(regionName+" "+cityName+" "+ areaName);
                addressMapper.insertSelective(address);
            } else {
                address = addressesList.get(0);
            }

            //查询生成该礼品码的订单
            List<OrderVo> orders = orderMapper.selectByOrderBatchNumber(orderGiftCode.getGenerateOrderId());

            String sendMemberId = "";
            String sendMemberName = "";

            // 订单添加时的时间是相同的
            int orderAddTime = DateUtil.unixTimeStampInt().intValue();

            for(OrderVo orderVo :orders){
                Order order = orderMapper.selectByPrimaryKey(orderVo.getOrderId());
                sendMemberId = order.getBuyerId()+"";
                sendMemberName = order.getBuyerName();
                OrderCommon orderCommon = orderCommonMapper.selectByPrimaryKey(order.getOrderId());
                int oldGoodsNum = orderCommon.getCodeNum();
                //相关订单商品
                List<OrderGoods> orderGoodsList = orderGoodsMapper.findOrderGoodsListByOrderId(order.getOrderId());
//                Integer codeNum = orderCommon.getCodeNum() != null ? orderCommon.getCodeNum() : 1;

                //插入新的订单信息
                order.setOrderAmount(order.getOrderAmount().divide(new BigDecimal(orderCommon.getCodeNum())));
                order.setGoodsAmount(order.getGoodsAmount().divide(new BigDecimal(orderCommon.getCodeNum())));
                order.setShippingFee(order.getShippingFee().divide(new BigDecimal(orderCommon.getCodeNum())));
                order.setOrderState("20");
                order.setOrderBatchNumber(ORDER_BATCH_NUMBER);
                order.setAddTime(orderAddTime);
                order.setBuyerId(member.getMemberId());
                order.setBuyerName(member.getMemberName());
                order.setBuyerEmail(member.getMemberEmail());
                order.setPaymentCode("3");//领取
                order.setOrderId(null);
                order.setOrderSn(SerialNumGenerator.getOrderSn(SerialNumGenerator.ORDERCH_WEBCHART));
                orderMapper.insertSelective(order);
                orderCommon.setOrderId(order.getOrderId());
                orderCommon.setReciverName(address.getTrueName());
                orderCommon.setReciverInfo(JacksonsUtil.newInstance().readAsString(address));
                orderCommon.setReciverProvinceId(address.getAreaId());
                orderCommon.setReciverCityId(address.getCityId());
                orderCommon.setPostType(1);
                orderCommon.setPayType(3);
                orderCommon.setCodeNum(1);
                orderCommon.setGiftCode(giftCode);
                // Integer的null数据 保存到数据库后变成了 0
               // orderCommonMapper.insertSelective(orderCommon);
                orderCommonMapper.insert(orderCommon);

                // 商品信息（短信发送使用）
                String goodsInfo = "";
                //插入领取的订单商品数据
                for (OrderGoods orderGoods : orderGoodsList) {
                    orderGoods.setRecId(null);
                    orderGoods.setGoodsNum(orderGoods.getGoodsNum() / oldGoodsNum);
                    orderGoods.setOrderId(order.getOrderId());
                    //orderGoodsMapper.insertSelective(orderGoods);
                    orderGoodsMapper.insert(orderGoods);

                    // xx商品N件（个）、xx商品N件（个）
                    if (!"".equals(goodsInfo)) {
                        goodsInfo = goodsInfo + "、";
                    }
                    goodsInfo = goodsInfo + orderGoods.getGoodsName() + "商品" + orderGoods.getGoodsNum() + "件（个）";
                }

                // 短信发送
                // 自己购买时，付完款后就发短信
                // 送礼时，收礼者填完收货地址后再发短信
                System.out.println("订单【"+order.getOrderId()+"】的短信发送开始。。。。。");
                try {
                    String phoneNum = settingService.getSettingInfo(SettingNameEnum.OPERATION_MOBILE_PHONE);
                    MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("order_payment_success");

                    Map<String, Object> smsMap = new HashMap<String, Object>();
                    smsMap.put("moblieNumber", phoneNum);
                    // 【央联E家】你好，2018年x月x日xx时，您的xx店铺，xx商品被某某拍下N件（个），并已经付款，请及时发货！
                    // 【央联E家】你好，{1}，您的{2}店铺，{3}拍下了{4}，并已经付款，请及时发货！
                    String[] params = new String[4];
                    //  yyyy年MM月dd日 HH时mm分ss秒
                    String strDateTime =  DateUtil.toGbkStrDate(order.getPaymentTime());
                    strDateTime = strDateTime.substring(0, strDateTime.length() - 3);
                    params[0] = strDateTime;  // yyyy年MM月dd日 HH时mm分
                    params[1] = order.getStoreName();
                    params[2] = order.getBuyerName();
                    // xx商品N件（个）、xx商品N件（个）
                    params[3] = goodsInfo;
                    smsMap.put("params", params);

                    messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
                } catch (Exception e){
                    e.printStackTrace();
                    logger.error("订单【" + order.getOrderId() + "】的短信发送失败：", e);
                }finally {
                    System.out.println("订单【" + order.getOrderId() + "】的短信发送结束。。。。。");
                }
            }

            //写入礼品码领取记录表
            GiftReceiveRecord giftReceiveRecord = new GiftReceiveRecord();
            giftReceiveRecord.setrMemberId(member.getMemberId().toString());
            giftReceiveRecord.setrOrderId(orderGiftCode.getGenerateOrderId());
            giftReceiveRecord.setrSendMemberId(sendMemberId);
            giftReceiveRecord.setrSendMemberName(sendMemberName);
            giftReceiveRecord.setrReceiveMobile(address.getMobPhone());
            giftReceiveRecord.setrReceiveName(address.getTrueName());
            giftReceiveRecord.setrReceiveAddress(address.getAreaInfo() + " " + address.getAddress());
            giftReceiveRecord.setrGiftCode(orderGiftCode.getGiftCode());
            giftReceiveRecord.setCreateTime(DateUtil.getCurrentDateTime());
            giftReceiveRecord.setCreaterId(member.getMemberId());
            giftReceiveRecord.setCreateName(member.getMemberName());
            giftReceiveRecordMapper.insertSelective(giftReceiveRecord);

            //更新礼品码使用状态
            orderGiftCode.setUseOrderId(ORDER_BATCH_NUMBER+"");
            orderGiftCode.setCodeState(2);
            orderGiftCodeMapper.updateByPrimaryKeySelective(orderGiftCode);

            ajaxReturnData.setResult(true);
//            ajaxReturnData.setReturnStr();
            ajaxReturnData.setMessage("领取成功");
        }

        return ajaxReturnData;
    }

    /****
     * 领取礼品吗
     *
     * @param memberId
     * @param orderId
     * @return
     */
    @Override
    @Transactional
    public synchronized AjaxReturnData reqGiftCode(Integer memberId, Integer orderId) throws Exception{
        AjaxReturnData ajaxReturnData = new AjaxReturnData();
        OrderGiftCode record = new OrderGiftCode();
        record.setGenerateOrderId(orderId + "");
        record.setCodeState(1);
        List<OrderGiftCode> list = orderGiftCodeMapper.selectByCondition(record);
        if (list.size() > 0) {
            record = list.get(0);
            record.setCodeState(2);
            record.setUseMemberId(memberId);
            record.setUseTime(DateUtil.getCurrentDateTime());
            orderGiftCodeMapper.updateByPrimaryKeySelective(record);
            ajaxReturnData.setResult(true);
            ajaxReturnData.setReturnStr(record.getGiftCode() + "-" + orderId);
            ajaxReturnData.setMessage("领取成功");
        } else {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setMessage("未领取到");
        }
        return ajaxReturnData;
    }

    /**
     * 判断礼品码是否可以正常使用
     *
     * @param giftCode
     * @return
     */
    @Override
    public boolean checkGiftCodeStatus(String giftCode) {

        OrderGiftCode orderGiftCode = orderGiftCodeMapper.selectByGiftCode(giftCode);

        if(orderGiftCode!=null){
            switch (orderGiftCode.getCodeState()){
                case 1:{
                    logger.debug(giftCode+"正常");return true;
                }
                case 2:{
                    logger.debug(giftCode+"已失效");return false;
                }case 3:{
                    logger.debug(giftCode+"已注销");return false;
                }default:{
                    logger.debug(giftCode+"未知状态");return false;
                }
            }
        }else{
            logger.debug(giftCode+"不存在");
            return false;
        }

//        if(orderGiftCode.getCodeState() == 1){
//            logger.debug(giftCode+"正常");
//            return true;
//        }else if (orderGiftCode.getCodeState() == 2){
//            logger.debug(giftCode+"已失效");
//            return false;
//        }else if(orderGiftCode.getCodeState() == 3){
//            logger.debug(giftCode+"已注销");
//            return false;
//        }else{
//
//        }
    }

    /**
     * 获取礼品码中的礼品
     *
     * @param giftCode
     * @return
     */
    @Override
    public List<OrderGoods> listGoodsByGiftCode(String giftCode) {

        OrderGiftCode orderGiftCode = orderGiftCodeMapper.selectByGiftCode(giftCode);

        List<OrderVo> orders = orderMapper.selectByOrderBatchNumber(orderGiftCode.getGenerateOrderId());
        List<OrderGoods> orderGoodsList = new ArrayList<OrderGoods>();
        for(OrderVo orderVo:orders){
            List<OrderGoods> orderGoodsList1 = orderGoodsMapper.findOrderGoodsListByOrderId(orderVo.getOrderId());
            orderGoodsList.addAll(orderGoodsList1);
        }
        return orderGoodsList;
    }

    public String areaName(Integer areaId){
        if(areaId!=null){
            Area area = areaMapper.selectByPrimaryKey(areaId);
            return area!=null?area.getAreaName():"";
        }
        return "";
    }
}
